﻿$(function () {
    $('.configButton button[data-querytype]').die('click').live('click', function () {
        getMySelectedColumns($(this).attr('data-querytype'), function () {
            $('.bgWrapper').show();
            mutipleSelect();
        });
    });

    $('.bgWrapper .cancel').die('click').live('click', function () {
        $('.bgWrapper').hide();
    });

    var mutipleSelect = function () {

        var container = $('.multipleSelect'),
            leftSelect = container.find('select#allSelectable'),
            rightSelect = container.find('select#selected'),
            removeBtn = container.find('button#remove'),
            removeAllBtn = container.find('button#removeAll'),
            addBtn = container.find('button#add'),
            addAllBtn = container.find('button#addAll');

        //检查右边选项个数决定移除按钮是否可点击
        var checkRemove = function () {
            if (!rightSelect.find('option').length) {
                removeBtn.attr('disabled', 'disabled');
                removeAllBtn.attr('disabled', 'disabled');
            } else {
                removeBtn.removeAttr('disabled');
                removeAllBtn.removeAttr('disabled');
            }

        };
        //检查右边选项个数等于左边个数决定添加按钮是否可点击
        var checkAdd = function () {
            if (rightSelect.find('option').length == leftSelect.find('option').length) {
                addBtn.attr('disabled', 'disabled');
                addAllBtn.attr('disabled', 'disabled');
            } else {
                addBtn.removeAttr('disabled');
                addAllBtn.removeAttr('disabled');
            }
        };
        //移除
        var remove = function (selected) {
            selected.remove();
            checkRemove();
            checkAdd();
        };
        //添加
        var add = function (selected) {
            selected.each(function () {
                if (!rightSelect.find('option[value="' + $(this).val() + '"]').length) {
                    rightSelect.append($(this).clone());
                }
            });

            checkAdd();
            checkRemove();
        };

        checkRemove();
        checkAdd();

        removeBtn.unbind('click').bind('click', function () {
            remove(rightSelect.find('option:selected'));
        });

        removeAllBtn.unbind('click').bind('click', function () {
            remove(rightSelect.find('option'));
        });

        leftSelect.find('option').die('dblclick').live('dblclick', function (e) {
            add($(e.currentTarget));
        });

        addBtn.unbind('click').bind('click', function () {
            add(leftSelect.find('option:selected'));
        });

        addAllBtn.unbind('click').bind('click', function () {
            add(leftSelect.find('option'));
        });

        rightSelect.find('option').die('dblclick').live('dblclick', function (e) {
            remove($(e.currentTarget));
        });

    };

});

//从数据库获取我设置的维度和显示列
var getMySelectedColumns = function (queryType, callback) {

    $.ajax({
        url: '/ReportView/GetMySelectedColumns',
        cache:false,
        data: {
            QueryType: queryType
        },
        success: function (res) {
            if (res) {
                var selected = res.selectedColumns,
                    allColumns = res.allColumns,
                    groupCode = '',
                    groupName = '';

                $('select#allSelectable').html('');
                $('select#selected').html('');
                $.each(allColumns, function (i, item) {
                    $('select#allSelectable').append('<option value="' + item.Field + '" data-column="' + item.ID + '">' + item.Name + '</option>');
                    if (item.GroupCode)
                        groupCode = item.GroupCode;
                    if (item.GroupName)
                        groupName = item.GroupName;
                });

                $.each(selected, function (i, item) {
                    $('select#selected').append('<option value="' + item.Field + '" data-column="' + item.ColumnID + '">' + item.Name + '</option>');
                    if (item.GroupCode)
                        groupCode = item.GroupCode;
                    if (item.GroupName)
                        groupName = item.GroupName;
                });

                if (groupCode) {
                    $('#groupList').val(groupCode);
                }

                if (typeof callback == "function") callback(groupName, selected, allColumns);
            }
        }
    });

};

//更新我选择要展现的列和维度
var updateSelectedColumns = function (queryType, callback) {

    var columns = [];

    var selectedColumns = $('select#selected').find('option'),
        groupCode = $('#groupList').val(),
        groupName = $('#groupList option:selected').text();

    $(selectedColumns).each(function () {
        columns.push({
            GroupName: groupName,
            GroupCode: groupCode,
            ColumnID: $(this).attr('data-column'),
            IsSelected: '1'
        });
    });


    $.ajax({
        url: '/ReportView/UpdateSelectedColumns',
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify({
            QueryType: queryType,
            Columns: columns
        }),
        success: function () {
            if (typeof callback == "function") callback();
        }
    });
};

var ReportViewInsp = {};
//获取查询条件
var getQueryData = ReportViewInsp.getQueryData = function (container) {
    var query = {};
    container.find('[data-source]').each(function () {
        if ($(this).hasClass('easyui-datebox')) {
            query[$(this).attr('data-source')] = $(this).datebox('getValue') == "" ? null : $(this).datebox('getValue');
        } else if ($(this).attr('type') == "checkbox") {
            query[$(this).attr('data-source')] = $(this).is(':checked');
        } else {
            query[$(this).attr('data-source')] = $(this).val();
        }
    });
    return query;
};

//获取包括维度在内的所有查询条件
ReportViewInsp.allQueryData = function (container, tableID, groupCode) {
    var query = ReportViewInsp.getQueryData(container);
    var cond = "";
    var rows = $('#' + tableID).datagrid('getChecked');
    $.each(rows, function (i, row) {
        if ($.trim(row[groupCode]) != '总计' && $.trim(row[groupCode]))
            cond += row[groupCode] + ";";
    });
    query[groupCode] = cond + ";;";

    if (tableID == "searchGroupList" && groupCode == "HostAddress") {
        query["CreateTime_From"] = query["CalculateDate_From"];
        query["CreateTime_To"] = query["CalculateDate_To"];
    }

    return query;
};

var enableButton = function (isEnable) {
    if (isEnable) {
        $('button').removeAttr('disabled');
    }
    else {
        $('button').attr('disabled', true);
    }
};

//获取报表导出的查询数据
var getExportQuery = function () {
    return ReportViewInsp.allQueryData($('#searchParam'), 'searchGroupList', getGroupCode());
};
//获取报表导出的导出类型['任务综合']
var getQueryType = function () {
    return $('[data-querytype]').attr('data-querytype');
};
//获取排序参数
var getSortOptions = function () {
    return {
        sort: $('#searchList').datagrid('options').sortName,
        order: $('#searchList').datagrid('options').sortOrder
    };
};

var getReportViewData = function () {
    return {
        GroupName: getGroupName(),
        GroupTitleList: getTitleList('searchGroupList'),
        GroupDataList: getGroupData(),
        DetailTitleList: getTitleList('searchList'),
        DetailFieldList: getFieldList('searchList')
    };

};
//获取维度值
var getGroupCode = function () {
    return $('[data-groupCode]').attr('data-groupCode');
};
//获取维度显示值
var getGroupName = function () {
    return $('[data-groupName]').attr('data-groupName');
};

//获取分组头部
var getTitleList = function (tableID) {
    if ($('#' + tableID).length) {
        var data = $('#' + tableID).datagrid('options'),
            columns = data.columns[0],
            list = [];

        $.each(columns, function (i, col) {
            if (!col.checkbox && col.title) {
                list.push(col.title);
            }
        });

        return list;
    }
};
//获取分组数据结果
var getGroupData = function () {
    var data = $('#searchGroupList').datagrid('getData'),
        rows = data.rows,
        columns = $('#searchGroupList').datagrid('options').columns[0],
        list = [, ];

    $.each(rows, function (i, row) {
        var rowdata = [];
        $.each(columns, function (j, col) {
            if (!col.checkbox && col.title) {
                if (typeof col.formatter == "function") {
                    rowdata.push(col.formatter(row[col.field]));
                } else {
                    rowdata.push(row[col.field]);
                }
            }
        });
        list[i] = rowdata.join(',');
    });

    return list;
}

var getFieldList = function (tableID) {
    if ($('#' + tableID).length) {
        return $('#' + tableID).datagrid('getColumnFields');
    }
};


///utility
/*
 * Array.prototype.includes 数组中是否包含某个元素
 */
if (![].includes) {
    Array.prototype.includes = function (searchElement /*, fromIndex*/) {
        if (this === undefined || this === null) {
            throw new TypeError('Cannot convert this value to object');
        }
        var O = Object(this);
        var len = parseInt(O.length) || 0;
        if (len === 0) {
            return false;
        }
        var n = parseInt(arguments[1]) || 0;
        var k;
        if (n >= 0) {
            k = n;
        } else {
            k = len + n;
            if (k < 0) k = 0;
        }
        while (k < len) {
            var currentElement = O[k];
            if (searchElement === currentElement ||
               (searchElement !== searchElement && currentElement !== currentElement)) {
                return true;
            }
            k++;
        }
        return false;
    }
}

if (!Array.prototype.forEach) {

    Array.prototype.forEach = function forEach(callback, thisArg) {

        var T, k;

        if (this == null) {
            throw new TypeError("this is null or not defined");
        }

        // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
        var O = Object(this);

        // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
        // 3. Let len be ToUint32(lenValue).
        var len = O.length >>> 0; // Hack to convert O.length to a UInt32

        // 4. If IsCallable(callback) is false, throw a TypeError exception.
        // See: http://es5.github.com/#x9.11
        if ({}.toString.call(callback) !== "[object Function]") {
            throw new TypeError(callback + " is not a function");
        }

        // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
        if (thisArg) {
            T = thisArg;
        }

        // 6. Let k be 0
        k = 0;

        // 7. Repeat, while k < len
        while (k < len) {

            var kValue;

            // a. Let Pk be ToString(k).
            //   This is implicit for LHS operands of the in operator
            // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
            //   This step can be combined with c
            // c. If kPresent is true, then
            if (Object.prototype.hasOwnProperty.call(O, k)) {

                // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
                kValue = O[k];

                // ii. Call the Call internal method of callback with T as the this value and
                // argument list containing kValue, k, and O.
                callback.call(T, kValue, k, O);
            }
            // d. Increase k by 1.
            k++;
        }
        // 8. return undefined
    };
}

Array.prototype.uniquelize = function () {
    var ra = new Array();
    for (var i = 0; i < this.length; i++) {
        if (!ra.includes(this[i])) {
            ra.push(this[i]);
        }
    }
    return ra;
};


Array.union = function (a, b) {
    return a.concat(b).uniquelize();
};
